﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using System.Web;
using System.IO;

using MES.DataGateway.OracleDAL;
using MES.DataGateway.SyncEntity;
using MES.DataGateway.Common;
using MES.DataGateway.SyncCommon;
using MES.DataGateway.SyncInterface;
using MES.DataGateway.StandardEntity;
using System.Text.RegularExpressions;

namespace MES.DataGateway.StandardDataSync
{
    /// <summary>
    /// add by yuxj 20170410 从TC中增加检验项,先开发为API存储，后改为直接插入table
    /// </summary>
    public class Checks
    {
        private AssistantClass m_Assistant = new AssistantClass();
        private string m_DataFilePath = "";
        private StandardDAL m_dal;
        public string DataFilePath
        {
            get { return m_DataFilePath; }
            set { m_DataFilePath = value; }
        }
        public void Execute()
        {
            try
            {
                m_Assistant.DataFilePath = m_DataFilePath;
                m_dal = new StandardDAL();
                ReadXML(m_DataFilePath);
            }
            catch (Exception myError)
            {
                Log.WriteLog(DateTime.Now.ToString(), 1, "Checks.Execute" + myError.Message);
            }
        }

        private void InsertIntoStepCheckPoint(string strWorkflowstepid, string strProductid, List<CheckInfoEnity> strGcList)
        {
            if (strGcList.Count == 0)
            {
                return;
            }
            string CheckType = "3";//update:wangjh 20220518 默认1改为3
            string CheckInputType = "1";
            string intNum = "1";
            string CheckPointNote = "";
            string TCCheckPointNote = "";
            string TCDrawingRequire = "";
            string DrawingRequire = ""; 

            SortedList<string, object> list;
            for (int i = 0; i < strGcList.Count; i++)
            {
                switch (strGcList[i].CheckTypeName) //add by zhangrj 2021-12-8
                {
                    case "设计特性":
                        CheckType = "3"; break;
                    case "过程参数":
                        CheckType = "4"; break;
                    case "振动攻关":
                        CheckType = "5"; break;
                    default:
                        break;
                }
                string strSymbol = strGcList[i].GZSymbol;//关键特性标识
                TCCheckPointNote = strGcList[i].strCheckContent;
                if ( string.IsNullOrWhiteSpace(strGcList[i].DrawingRequire ))
                {
                    continue;
                }
                if (string.IsNullOrWhiteSpace(strGcList[i].CheckNO))
                {
                    continue;
                }
                string id="";//唯一id
                /*
                 * 是否存在相同检测项判断，--新增参数字段判断 edit by zhangrj 20250106
                 */
                if (m_dal.IsExistStepCheckPoint2("", strWorkflowstepid, strGcList[i].stepinfoId, strSymbol,
                    strGcList[i].CheckNO, strGcList[i].DrawingRequire, strGcList[i].BubbleNumber, CheckType,
                    CheckInputType, strGcList[i].KeyCheck, strGcList[i].QualityCheck, TCCheckPointNote, ref id))//strProductid
                    continue;
                //m_dal.IsExistStepCheckPoint2("", strWorkflowstepid, strGcList[i].stepinfoId, strSymbol,
                //    strGcList[i].CheckNO, strGcList[i].DrawingRequire, strGcList[i].BubbleNumber, ref id);

                string strDraw = string.Empty;
                TCDrawingRequire = strGcList[i].DrawingRequire;
                CheckPointNote = converdraw(TCCheckPointNote);
                DrawingRequire = converdraw(TCDrawingRequire);

                list = new SortedList<string, object>();
                list.Add("CheckInputType", string.IsNullOrWhiteSpace(CheckInputType) ? 0 : int.Parse(CheckInputType));
                list.Add("CheckNO", string.IsNullOrWhiteSpace(strGcList[i].CheckNO) ? 0 : int.Parse(strGcList[i].CheckNO));
                list.Add("CheckPointNote", CheckPointNote);
                list.Add("CheckType", CheckType);
                list.Add("IntNum", string.IsNullOrWhiteSpace(strGcList[i].InputNum) ? 0 : int.Parse(strGcList[i].InputNum));//modify by longb 2024.04.15
                list.Add("KeyCheck", string.IsNullOrWhiteSpace(strGcList[i].KeyCheck) ? 0 : int.Parse(strGcList[i].KeyCheck));
                list.Add("MeopCheck", string.IsNullOrWhiteSpace(strGcList[i].MeopCheck) ? 0 : int.Parse(strGcList[i].MeopCheck));
                list.Add("strSymbol", strSymbol);//modify:wangjh 2023-1-9 strCheckName->strSymbol
                list.Add("Productid", "");//strProductid
                list.Add("QualityCheck", string.IsNullOrWhiteSpace(strGcList[i].QualityCheck) ? 0 : int.Parse(strGcList[i].QualityCheck));
                list.Add("Workflowstepid", strWorkflowstepid);
                list.Add("TCCheckPointNote", TCCheckPointNote);
                list.Add("DrawingRequire", DrawingRequire);
                list.Add("TCDrawingRequire", TCDrawingRequire);
                if (!string.IsNullOrWhiteSpace(strGcList[i].stepinfoId)) {
                    list.Add("StepInfoID", strGcList[i].stepinfoId);
                }
                list.Add("CheckMethod", strGcList[i].CheckMethod);//add by longb 2023-05-06 检测手段
                list.Add("BaseValue", strGcList[i].BaseValue);//add by longb 2022-10-10
                list.Add("CeiFloat", strGcList[i].CeiFloat);//add by longb 2022-10-10
                list.Add("FloorFloat", strGcList[i].FloorFloat);//add by longb 2022-10-10 
                list.Add("BubbleNumber", strGcList[i].BubbleNumber);//add by wangjh 2023-1-10 气泡号
                list.Add("IsSPC", strGcList[i].IsSPC);//add by wangjh 2023-3-13 是否SPC
                list.Add("IsInstall", strGcList[i].IsInstall);//add by wangjh 2023-3-13 是否安装单
                list.Add("IsDisassemble", strGcList[i].IsDisassemble);//add by wangjh 2023-3-13 是否拆卸单
                list.Add("IsNotice", strGcList[i].IsNotice);//add by wangjh 2023-3-13 是否通知单
                list.Add("IsReturn", strGcList[i].IsReturn);//add by wangjh 2023-3-13 是否返回单
                list.Add("IsCompp", strGcList[i].IsCompp);//add by wangjh 2023-3-13 是否综合性能表

                list.Add("SingLesign", strGcList[i].SingLesign);//add by longb 2024-4-15 单向标识
                list.Add("CheckRequire", strGcList[i].CheckRequire);//add by longb 2024-4-15 规定值代号
                list.Add ("StepCheckPointId",id);//唯一id
                list.Add("CheckRatio", strGcList[i].CheckRatio);
                m_dal.InsertIntoStepCheckPointTable(list);
            }
        }

        private string converdraw(string CheckPointNote)
        {
            string strDraw = "";
            try
            {
                strDraw = m_Assistant.CheckDraw(CheckPointNote);
                if (strDraw == string.Empty)
                {
                    strDraw = CheckPointNote;
                }
            }
            catch (Exception e)
            {
                strDraw = CheckPointNote;
            }
            return strDraw;
        }


        private void ReadXML(string strPath)
        {
            string strSpecName = string.Empty, strSpecVersion = string.Empty, strProdcutName = string.Empty;
            string strProductVersion = string.Empty, strProductDesc = string.Empty;
            string strWorkflowitemID = string.Empty, strWorkflowRevision = string.Empty;
            XmlDocument myxml = new XmlDocument();
            myxml.Load(strPath);

            //获取件号信息
            XmlNode stu = null;
          
            strProdcutName = m_Assistant.GetProductName(strPath)[0];
            m_Assistant.ReplaceProductH(myxml, ref strProdcutName);

            //strProdcutName = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/product/item/item_revision_id");
            strProductVersion = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/item_revision_id");
            strWorkflowRevision = stu.InnerText.Trim();
            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/item_id");
            strWorkflowitemID = stu.InnerText.Trim();

            stu = myxml.SelectSingleNode("/Root/WorkFlow/MEOPs");
            //add by yuxj
            if (stu == null)
                return;

            string strProductid = m_dal.GetProductId(strProdcutName, strProductVersion);
            if (string.IsNullOrEmpty(strProductid))
                return;

            foreach (XmlNode node in stu.ChildNodes)
            {
                if (node.Name != "MEOP")
                    continue;
                if (node.ChildNodes.Count == 0)
                { continue; }

                strSpecName = string.Format("{0}-{1}", node.SelectSingleNode("ly2meop_no").InnerText.Trim(),
                               node.SelectSingleNode("object_name").InnerText.Trim());
                strSpecVersion = node.SelectSingleNode("item_revision_id").InnerText.Trim();

                DataTable steplist = m_dal.GetWorkflowstepId(strSpecName, strWorkflowitemID, strWorkflowRevision);
                string strWorkflowstepid = steplist.Rows[0]["WORKFLOWSTEPID"].ToString();

                //yuxj20221031 工序和工步上都可能存在检测项，也可能工序和工步同时出现检测项
                //此处取两个地方检测项之和
                //工序上的检测项
                XmlNode nodeCheck = node.SelectSingleNode("Checks");
                if (nodeCheck != null)
                {
                    CreateStepCheck(strProductid, strWorkflowstepid, "", nodeCheck);
                }    
               
                //工步上的检测项
                XmlNode nodeSteps = node.SelectSingleNode("STEPs");
                if (nodeSteps == null)
                    continue;
                foreach (XmlNode _node in nodeSteps.ChildNodes)
                {
                    nodeCheck = _node.SelectSingleNode("Checks");
                    if (nodeCheck == null)
                        continue;
                    if (nodeCheck.ChildNodes.Count == 0)
                        continue;
                    string stepInfoName = string.Format("{0}-{1}", strWorkflowstepid, _node.SelectSingleNode("item_id").InnerText.Trim());//工步名
                    string stepInfoRevision = _node.SelectSingleNode("item_revision_id").InnerText.Trim();//工步版本
                    DataTable stepinfodt = m_dal.GetRDOTable("StepInfo", "StepInfoName", stepInfoName, "Revision", stepInfoRevision);
                    if (stepinfodt.Rows.Count == 0)
                        continue;
                    CreateStepCheck(strProductid, strWorkflowstepid, stepinfodt.Rows[0]["StepInfoID"].ToString(), nodeCheck);
                }
            }
        }


        private void CreateStepCheck(string strProductid, string strWorkflowstepid,string stepinfoId, XmlNode nodeCheck)
        {
            List<CheckInfoEnity> checkList = new List<CheckInfoEnity>();
            CheckInfoEnity entityTmp = new CheckInfoEnity();

            //yuxj20221118创建之前先清理旧的检测项
            //工序检测项和工步检测项
            //不用清除，担心已经传过来的工艺已经被开开并使用（尽管TC有限制同版本同工艺必须有相同的检测项）
            //m_dal = new StandardDAL();
            //m_dal.ClearStepCheckPoint(strWorkflowstepid, stepinfoId);

            foreach (XmlNode OPnode in nodeCheck.ChildNodes)
            {
                if (OPnode.Name != "Check")
                    continue;
                if (OPnode.ChildNodes.Count == 0)
                    continue;

                entityTmp = new CheckInfoEnity();
                foreach (XmlNode Checksnode in OPnode.ChildNodes)
                {
                    if (Checksnode.Name == "GZSymbol")
                    {
                        entityTmp.GZSymbol  = Checksnode.InnerText;
                    }
                    else if (Checksnode.Name == "CheckContent")
                    {
                        entityTmp.strCheckContent = Checksnode.InnerText.Trim().Replace("<$s>", "°").Replace("<#A>", "×");//modify by longb 2024-01-17
                    }

                    else if (Checksnode.Name == "CheckNO")
                    {
                        entityTmp.CheckNO = Checksnode.InnerText;
                    }
                    else if (Checksnode.Name == "DrawingRequire")
                    {
                        entityTmp.DrawingRequire = Checksnode.InnerText.Replace("<$s>", "°").Replace("<#A>", "×");//modify by longb 2024-01-17
                    }
                    else if (Checksnode.Name == "KeyCheck")
                    {
                        if (Checksnode.InnerText.Trim() == "true")
                        {
                            entityTmp.KeyCheck = "1";
                        }
                        else
                        {
                            entityTmp.KeyCheck = "0";
                        }
                    }
                    else if (Checksnode.Name == "MeopCheck")
                    {
                        if (Checksnode.InnerText.Trim() == "true")
                        {
                            entityTmp.MeopCheck = "1";
                        }
                        else
                        {
                            entityTmp.MeopCheck = "0";
                        }
                    }
                    else if (Checksnode.Name == "QualityCheck")
                    {
                        if (Checksnode.InnerText.Trim() == "true")
                        {
                            entityTmp.QualityCheck = "1";
                        }
                        else
                        {
                            entityTmp.QualityCheck = "0";
                        }
                    }
                    else if (Checksnode.Name == "CheckType") //add by zhangrj 2021-12-8
                    {
                        entityTmp.CheckTypeName = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "CheckMethod") //add by longb 2023-05-06 检测手段
                    {
                        entityTmp.CheckMethod = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "ToleranceSize")//add by longb 2022-10-09【公差尺寸】
                    {
                        entityTmp.BaseValue = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "UpperTolerance")//add by longb 2022-10-09【上公差】
                    {
                        entityTmp.CeiFloat = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "LowerTolerance")//add by longb 2022-10-09【下公差】
                    {
                        entityTmp.FloorFloat = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "CheckName")//气泡号,tc将此字段更改存储为气泡号 add:Wangjh 2023-1-10
                    {
                        entityTmp.BubbleNumber  = Checksnode.InnerText.Trim();
                    } else if (Checksnode.Name == "SPC")//是否SPC
                    {
                        entityTmp.IsSPC  = Checksnode.InnerText.Trim()=="true"?1:0;
                    } else if (Checksnode.Name == "Install")//是否安装单
                    {
                        entityTmp.IsInstall  = Checksnode.InnerText.Trim()=="true"?1:0;
                    } else if (Checksnode.Name == "Disassemble")//是否拆卸单
                    {
                        entityTmp.IsDisassemble  = Checksnode.InnerText.Trim()=="true"?1:0;
                    } else if (Checksnode.Name == "Notice")//是否通知单
                    {
                        entityTmp.IsNotice  = Checksnode.InnerText.Trim()=="true"?1:0;
                    } else if (Checksnode.Name == "Return")//是否返回单
                    {
                        entityTmp.IsReturn  =Checksnode.InnerText.Trim()=="true"?1:0;
                    } else if (Checksnode.Name == "ComprehensivePerformance")//是否综合性能表
                    {
                        entityTmp.IsCompp  = Checksnode.InnerText.Trim()=="true"?1:0;
                    }
                    else if (Checksnode.Name == "CheckRatio")//检测比例
                    {
                        entityTmp.CheckRatio = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "OnewayIdentify")//单向标识 add by longb 2024.04.15
                    {
                        entityTmp.SingLesign = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "CheckRequire")//规定值代号 add by longb 2024.04.15
                    {
                        entityTmp.CheckRequire = Checksnode.InnerText.Trim();
                    }
                    else if (Checksnode.Name == "Quantity")//检测数量 add by longb 2024.04.15
                    {
                        entityTmp.InputNum = string.IsNullOrWhiteSpace(Checksnode.InnerText.Trim()) ? "1" : Checksnode.InnerText.Trim();
                    }
                }
                entityTmp.stepinfoId = stepinfoId;//add:Wangjh 20220831 工步
                checkList.Add(entityTmp);
            }
            //保存数据

            //modify by yangsj 20170418
            InsertIntoStepCheckPoint(strWorkflowstepid, strProductid, checkList);
        }


    }

    class CheckInfoEnity
    {
        public string stepinfoId = "";//工步id
        public string strCheckInfo = "";
        //public string strCheckName = "";
        public string strCheckContent = "";
        public string QualityCheck = "";
        public string MeopCheck = "";
        public string KeyCheck = "";
        public string CheckNO = "";
        public string DrawingRequire = "";
        public string CheckTypeName = "";//add by zhangrj 2021-12-8
        public string CheckMethod = "";//add by longb 2023-05-06 检测手段
        public string BaseValue = "";//add by longb 2022-10-09
        public string CeiFloat = "";//add by longb 2022-10-09
        public string FloorFloat = "";//add by longb 2022-10-09
        public string GZSymbol = "";//add:Wangjh 20230109 关键特性标识
        public string BubbleNumber = "";//add:Wangjh 20230109 气泡号
        public string CheckRatio = "";//add:Wangjh 20230706 检测比例
        public int  IsSPC = 0;//add:Wangjh 20230313 是否SPC
        public int IsInstall = 0;//add:Wangjh 20230313 是否安装单
        public int IsDisassemble = 0;//add:Wangjh 20230313 是否拆卸单
        public int IsNotice = 0;//add:Wangjh 20230313 是否通知单
        public int IsReturn = 0;//add:Wangjh 20230313 是否返回单
        public int IsCompp = 0;//add:Wangjh 20230313 是否综合性能表
        public string InputNum = "1";//add by longb 2024-04-15 录入次数
        public string SingLesign = "";//add by longb 2024-04-15 单向标识
        public string CheckRequire = "";//add by longb 2024-04-15 规定值代号
    }
}
